# -*- coding: utf-8 -*-
"""
Created on Sat Jul  6 23:24:42 2019

@author: user
在Linex终端输入：
export HTTP_PROXY="http://127.0.0.1:1080"
export HTTPS_PROXY="http://127.0.0.1:1080"
在windows终端输入：
set HTTP_PROXY="http://127.0.0.1:1080"
set HTTPS_PROXY="http://127.0.0.1:1080"
"""
import asyncio
# link against the asynchronous version of ccxt
import ccxt.async_support as ccxt
import pandas as pd
from pprint import pprint

# from datetime import datetime
# import numpy as np


async def ccxt_fetch_datas():

    # 创建交易所
    def create_exchange(exchange_name):
        exchange_class = getattr(ccxt, exchange_name)
        exchange = exchange_class(
                {'enableRateLimit': True}
                )
        '''
        'proxies': {
                'http': 'http://127.0.0.1:1080',
                'https': 'https://127.0.0.1:1080'
                },
                ,
                }
        exchange.proxies = {
                'http': 'http://127.0.0.1:1080',
                'https': 'https://127.0.0.1:1080'

        exchange.load_markets()
        '''
        return exchange

    # 获取交易对分钟线数据
    async def get_minute_candles(exchange_name, symbol, days):

        params = {'partial': False}
        since = exchange.milliseconds() - days * 24 * 60 * 60 * 1000
        candles = await exchange.fetch_ohlcv(symbol, '1m', since,
                                             days * 24 * 60, params)
        df = pd.DataFrame(candles, columns=['timestamp', 'open', 'high', 'low',
                                            'close', 'volume'])
        # df.set_index(pd.DatetimeIndex(df['timestamp'].map(
        #                        lambda x:exchange.iso8601(x))),inplace=True)
        df['timestamp'] = df['timestamp'].map(
                lambda x: exchange.iso8601(x)[0:10])
        file_name = '~/Python-for-Finance' + str(exchange_name) + '_' +\
            str(symbol) + '_minute_2year.csv'
        df.to_csv(file_name)
        exchange.close()
        return df
    # 获取交易所名称
    exchanges_name = ccxt.exchanges
    exchange_name = 'bitfinex'
    if exchange_name in exchanges_name:
        exchange = create_exchange(exchange_name)
        exchange_symbols = exchange.symbols
        days = 365 * 2
        candles_df = await get_minute_candles(exchange_name,
                                              exchange_symbols[0], days)
    else:
        print('There is no exchang_name:', exchange_name)
    return candles_df


if __name__ == '__main__':
    pprint(asyncio.get_event_loop().run_until_complete(ccxt_fetch_datas()))
